<script setup lang="ts">
import type { FormInstance } from 'element-plus'

import { useResetPwd, useSendSms } from '@fl/api/mall-api'
import { SubmitBtn } from '@fl/components'
import { ElForm, ElFormItem } from 'element-plus'
import { useRouter } from 'vue-router'

const { replace } = useRouter()

const { isPending: isPendingSendSms, mutate: mutateSendSms } = useSendSms()
const { isPending: isPendingResetPwd, mutate: mutateResetPwd } = useResetPwd()
const veryfyCodeFirstSending = ref(false)
const countdown = ref(0)
const verifyLabel = computed(() => {
    if (unref(veryfyCodeFirstSending)) {
        if (unref(countdown) > 0)
            return `${unref(countdown)}秒后重发`
        else
            return '重新发送'
    }
    else { return '发送验证码' }
})

const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive({
    code: '',
    mobile: '',
    password: '',
    repeatPassword: '',
})

function validateConfirmPassword(_rule: any, value: string, callback: Fn): void {
    if (value === '')
        callback(new Error('请再次输入密码'))
    else if (value !== ruleForm.password)
        callback(new Error('两次输入密码不一致!'))
    else
        callback()
}

const rules = reactive({
    code: [
        {
            message: '请输入验证码',
            required: true,
        },
    ],
    mobile: [
        {
            message: '请输入手机号',
            required: true,
        },
    ],
    password: [
        {
            message: '请输入密码',
            required: true,
        },
    ],
    repeatPassword: [
        {
            required: true,
            validator: validateConfirmPassword,
        },
    ],
})

async function submitForm(formEl: FormInstance | undefined) {
    if (!formEl)
        return

    const isValid = await formEl.validate()
    if (isValid) {
        mutateResetPwd(ruleForm, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                replace('/login')
            },
        })
    }
}

async function sendVerifyCode() {
    const isValid = await unref(ruleFormRef)!.validateField('mobile')
    if (isValid) {
        await verifySuccess()
    }
}

async function verifySuccess() {
    mutateSendSms({ mobile: ruleForm.mobile }, {
        onSuccess: () => {
            // 启动倒计时
            veryfyCodeFirstSending.value = true
            countdown.value = 60
            startCountdown()
        },
    })
}

function startCountdown() {
    const interval = setInterval(() => {
        countdown.value = countdown.value - 1
        if (unref(countdown) === 0)
            clearInterval(interval)
    }, 1000)
}
</script>

<template>
    <ElForm ref="ruleFormRef"
            label-position="top"
            :model="ruleForm"
            :rules="rules"
            @submit.prevent
    >
        <div class="mb-10 text-20 text-#da0004 font-bold">
            重置密码
        </div>

        <div class="mb-16 flex flex-col gap-12">
            <ElFormItem label="手机号"
                        prop="mobile"
            >
                <el-input v-model.trim="ruleForm.mobile"
                          placeholder="请输入手机号"
                          maxlength="11"
                          size="large"
                />
            </ElFormItem>
        </div>

        <div class="flex flex-col gap-12">
            <ElFormItem label="验证码"
                        prop="code"
            >
                <div class="flex w-full items-center">
                    <el-input v-model.trim="ruleForm.code"
                              placeholder="请输入验证码"
                              size="large"
                              minlength="6"
                              maxlength="6"
                              class="flex-1"
                    />

                    <SubmitBtn type="primary"
                               class="ml-8 h-40 w-100"
                               :disabled="countdown > 0"
                               :loading="isPendingSendSms"
                               @click="sendVerifyCode"
                    >
                        {{ verifyLabel }}
                    </SubmitBtn>
                </div>
            </ElFormItem>
        </div>

        <div class="flex flex-col gap-12">
            <ElFormItem label="密码"
                        prop="password"
            >
                <el-input v-model.trim="ruleForm.password"
                          type="password"
                          show-password
                          placeholder="请输入密码"
                          size="large"
                          maxlength="20"
                />
            </ElFormItem>
        </div>

        <div class="flex flex-col gap-12">
            <ElFormItem label="确认密码"
                        prop="repeatPassword"
            >
                <el-input v-model.trim="ruleForm.repeatPassword"
                          type="password"
                          show-password
                          placeholder="请输入密码"
                          size="large"
                          maxlength="20"
                />
            </ElFormItem>
        </div>

        <ElFormItem>
            <SubmitBtn type="primary"
                       native-type="submit"
                       class="mt-30 rounded-3 text-#fff lh-48 text-center w-full cursor-pointer"
                       size="large"
                       :loading="isPendingResetPwd"
                       @click="submitForm(ruleFormRef)"
            >
                确定
            </SubmitBtn>
        </ElFormItem>
    </ElForm>
</template>
